<!--  -->
<template>
    <view class="container">
        <u-cell-item title="请选择供货日期" :border-bottom="false" :arrow="false"></u-cell-item>
        <view class="week">
            <view @click="chooseDate(index)" v-for="(item,index) in date" :class="dateIndex==index?'activeDate':''" :key="item.day">
                <view>{{ item.day }}</view>
                <view>{{ item.dayOfWeek }}</view>
            </view>
        </view>
        <!-- 商品列表 -->
        <view style="padding: 0 20rpx;">
            <goodsItem  v-for="item in list" :hasDelBtn="false" :key="item.id" :acid="thisItem" :goods="item" @changeNum="setGoodNum" @taps="taps" @addCart="addCart"></goodsItem>
			
			<view>
				<u-loadmore margin-top="25" :status="status" />
			</view>
			
        </view>
        <!-- 结算 -->
        <view class="settle" v-if="thisItem&&thisItem.price_t">
            <view class="sum">
                跟团购买：<text class="text1 ov1">{{thisItem.goodsName}}</text><text class="text2">{{ thisItem.price_t }}</text>元
            </view>
            <view class="submit-btn"> 
                <u-button size="medium" @click="pay" hover-class="none" :custom-style="{background:'#07c061',color:'#fff',padding:'0 25rpx'}" :loading="loading" shape="circle">立即购买</u-button>
            </view>
        </view>
    </view>
</template>

<script>
//这里可以导入其他文件（比如：组件，工具js，第三方插件js，json文件，图片文件等等）
//例如：import 《组件名称》 from '《组件路径》';
import goodsItem from '@/components/goodsItem.vue';
var BigNumber = require('../../static/js/bignumber');

export default {
    //import引入的组件需要注入到对象中才能使用
    components: {
        goodsItem
    },
	
	props: {
		//需循环的标签列表
		list: {
			type: Array,
			default () {
				return [];
			}
		},
		
		//  加载状态
		status: {
			type: String,
			default: 'nomore'
		},
		
	},
	
    data() {
        //这里存放数据
        return {
            num:0,
            date:[],    // 日期
            dateIndex:0, // 当前高亮日期
            loading:false,
			sum:0,
			
			thisItem:{},
			cartList:'',
			
        };
    },
    //监听属性 类似于data概念
    computed: {
        
    },
    //监控data中的数据变化
    watch: {},
    //方法集合
    methods: {
		
		//  立即购买
		pay(){
			let  that = this;
			console.log(that.list)
			
			for (var i = 0; i < that.list.length; i++) {
				if(that.list[i].goodsId == that.thisItem.goodsId){
					that.thisItem = that.list[i];
					break;
				}
			}
			
			if(that.thisItem){
				let obj = {
					list:JSON.stringify([{goodsId:that.thisItem.goodsId,count:that.thisItem.num}]),
					day:that.thisItem.day,
					source:'goods'
				}
				console.log(obj)
				that.$u.api.addOrder(obj).then(res => {
					uni.showToast({title: res.msg,duration: 2000,icon:'none'});
					if(res.code == 0){
						
					}
				})
				
			}
		},
		
		getNext15Days() {
		  const result = [];
		  const today = new Date();
		  
		  for (let i = 0; i < 15; i++) {
		    const nextDay = new Date(today);
		    nextDay.setDate(today.getDate() + i);
		    
		    const day = nextDay.getDate();
		    const month = nextDay.getMonth() + 1;
		    const year = nextDay.getFullYear();
		    
		    const dayOfWeek = ['周日', '周一', '周二', '周三', '周四', '周五', '周六'][nextDay.getDay()];
		    
		    const formattedDate = `${year}-${month < 10 ? '0' : ''}${month}-${day < 10 ? '0' : ''}${day}`;
		    
		    result.push({ date: formattedDate, dayOfWeek, day:day});
		  }
		  
		  return result;
		},
		
		
        //获取当前日期后15天日期和周几
        getDay() {
            var date = new Date();
            var dateArr = [];
            for (var i = 1; i < 16; i++) {
                var dateObj = {};
                var dateStr = date.getFullYear() + '-' + (date.getMonth() + 1) + '-' + (date.getDate() + i);
                var week = new Date(Date.parse(dateStr)).getDay();
                dateObj.date = dateStr;
                dateObj.day =  date.getDate() + i;
                switch (week) {
                    case 0:
                        dateObj.week = '周日';
                        break;
                    case 1:
                        dateObj.week = '周一';
                        break;
                    case 2:
                        dateObj.week = '周二';
                        break;
                    case 3:
                        dateObj.week = '周三';
                        break;
                    case 4:
                        dateObj.week = '周四';
                        break;
                    case 5:
                        dateObj.week = '周五';
                        break;
                    case 6:
                        dateObj.week = '周六';
                        break;
                }
                dateArr.push(dateObj);
            }
            this.date = dateArr;
        },
        // 选择日期
        chooseDate(index){
            this.dateIndex = index;
			this.$emit('chooseDate',{index:index,date:this.date[index]})
        },
        // 设置商品数量
        setGoodNum({value,index}){
           let item = this.list.find(el=>el.goodsId == index);
           item.num = value;
		   this.thisValue(item) 
        },
		
		// 加入购物车
		addCart(good_id){
			let  that = this;
			let item = that.list.find(el=>el.goodsId == good_id.index);
			if(item.num <= 0){return false}
			
			let  findCartGood = '';
			for (var i = 0; i < that.cartList.length; i++) {
				if(good_id.index == that.cartList[i].goods_id){
				console.log(1096)
					findCartGood = that.cartList[i];
				}
			}
			
			console.log(findCartGood)
			
			if(findCartGood){
				let obj = {
					id:findCartGood.id,
					num:item.num,
					day:item.day
				}
				that.$u.api.editBuyCar(obj).then(res => {
					uni.showToast({title: res.msg,duration: 2000,icon:'none'});
					if(res.code == 0){
						that.sumFun();
					}
				})
			}else{
				let obj = {
					goodsId:item.goodsId,
					num:item.num,
					day:item.day
				}
				that.$u.api.addBuyCar(obj).then(res => {
					uni.showToast({title: res.msg,duration: 2000,icon:'none'});
					if(res.code == 0){
						that.sumFun();
					}
				})
			}
			
		},
		
		// 购物车数据
		getCartData(){
			let  that = this;
			that.$u.api.getCartData().then(ret => {
				if(ret.code == 0){
					if(ret.data&&ret.data.length){
						that.cartList = ret.data;
						uni.setTabBarBadge({
							index:1,
							text:JSON.stringify(ret.data.length*1)
						})
						
					}else{
						uni.removeTabBarBadge({index:1})
					}
				}else{
					uni.removeTabBarBadge({index:1})
				}
			})
		},
		
		
		//  计算加购物车金额
		sumFun(){
		    let sum =  BigNumber(0);
		    this.list.forEach(el=>{
		        sum = BigNumber(sum.plus(el.price*el.num));
		    })
		    this.sum = sum;
			this.getCartData();
		},
		
		taps(v){
			this.thisValue(v)
		},
		
		thisValue(v){
			console.log('触摸执行')
			console.log(v)
			this.thisItem = v;
			this.$forceUpdate()
		},
		
        
    },
    //生命周期 - 创建完成（可以访问当前this实例）
    created() {

    },
    //生命周期 - 挂载完成（可以访问DOM元素）
    mounted() {
        this.getDay();
		
		const next15Days = this.getNext15Days(); 
		this.date = next15Days;
		console.log(next15Days);
		this.getCartData();
		
    },
    beforeCreate() { }, //生命周期 - 创建之前
    beforeMount() { }, //生命周期 - 挂载之前
    beforeUpdate() { }, //生命周期 - 更新之前
    updated() { }, //生命周期 - 更新之后
    beforeDestroy() { }, //生命周期 - 销毁之前
    destroyed() { }, //生命周期 - 销毁完成
    activated() { }, //如果页面有keep-alive缓存功能，这个函数会触发
}
</script>
<style lang="scss" scoped>

	
.container{
    padding-bottom: 200rpx;
}
    .week{
        //flex布局横向滚动
        display: flex;
        overflow-x: scroll;
        white-space: nowrap;
        &>view{
            flex: 0 0 auto;
            width: 120rpx;
            text-align: center;
            padding: 10rpx 0;
        }
        //隐藏滚动条
        &::-webkit-scrollbar {
            display: none;
        }
        .activeDate{
            background-color: #07c061;
            color: #fff;
        }
    }
    .settle{
        position: fixed;
        bottom: 0;
        left: 0;
        width: 100%;
        height: 100rpx;
        // background-color: #07c061;
        background-color: #fff;
        box-shadow: 0 0 10rpx #ccc;
        z-index: 999;
        display: flex;
        align-items: center;
        justify-content: space-between;
        padding: 0 20rpx;
        box-sizing: border-box;
        .sum{
            font-size: 28rpx;
			display: flex;align-items: center;
			.text1{max-width: 57%;}
            .text2{
                font-size: 40rpx;
                color: #07c061;
            }
        }
        .submit-btn{
            margin-left: 40rpx;
        }
    }
	.ov1{display: -webkit-box !important;overflow: hidden;text-overflow: ellipsis;word-wrap: break-word;word-break: break-all;white-space: normal !important;-webkit-line-clamp: 1;-webkit-box-orient: vertical;}
</style>